﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WindowsDemo.Properties;
using EntityCodeBuilder.Entity;
using Kevin.SyntaxTextBox;

namespace WindowsDemo
{
    public partial class frmMain : Form
    {
        private SyntaxTextBox txtSyntax;
        public frmMain()
        {
            InitializeComponent();
            fb.ShowNewFolderButton = true;
            t = this.Text;
            CreateFileHelper.OverrideGetHashCode = chkOverrideGetHashCode.Checked;
            CreateFileHelper.OverrideEquals = chkOverrideEquals.Checked;
            CreateFileHelper.GenerateColumn = chkGenerateColumn.Checked;
        }

        private class cache
        {
            public List<TableColumn> dataSource { get; set; }
            public string tableCodes { get; set; }
        }

        private List<TableName> m_tables = new List<TableName>();
        private ConcurrentDictionary<string, cache> caches = new ConcurrentDictionary<string, cache>();
        private List<TableName> m_SelTables = new List<TableName>();

        #region "初始化datagridview数据"
        private void Form1_Load(object sender, EventArgs e)
        {
            LoadDatas();
        }
        #endregion

        public void LoadDatas()
        {
            try
            {
                caches.Clear();
                m_tables.Clear();
                dgTables.ClearSelection();
                m_tables = TableHelper.GetTables();
                dgTables.DataSource = m_tables;
                dgTables.ClearSelection();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "载入数据失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void RefreshColums()
        {
            ShowColums(rowIndex);
        }

        private void ShowColums(int rowIndex)
        {
            if (rowIndex < 0)
                return;
            if (m_tables == null || m_tables.Count == 0 || rowIndex >= (m_tables.Count))
                return;
            TableName tb = m_tables[rowIndex];
            ShowColums(tb);
        }

        private void ShowColums(TableName tbl)
        {
            cache ca;
            if (!caches.TryGetValue(tbl.Name, out ca))
            {
                try
                {
                    ca = new cache()
                    {
                        dataSource = TableHelper.GetColumnField(tbl.Name),
                        tableCodes = CreateFileHelper.BuilderCode(tbl).Replace("\n", "\r\n")
                    };
                    caches.AddOrUpdate(tbl.Name, k => ca, (k, c) => ca);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "载入数据失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    ca = null;
                }
            }
            if (ca != null)
            {
                dgColumns.DataSource = ca.dataSource;
                txtSyntax.Text = ca.tableCodes;
            }
        }


        private void btnGen_Click(object sender, EventArgs e)
        {
            m_SelTables.Clear();
            int iRow = 0;
            foreach (DataGridViewRow row in dgTables.Rows)
            {
                int iCol = 0;
                foreach (DataGridViewCell cell in row.Cells)
                {
                    if (iCol == 0)
                    {
                        bool ifcheck1 = Convert.ToBoolean(cell.FormattedValue);
                        if (ifcheck1)
                        {
                            TableName tb = m_tables[iRow];
                            m_SelTables.Add(tb);
                        }
                    }

                    iCol++;
                }

                iRow++;
            }


            CreateFileHelper.Create(m_SelTables, txtPath.Text.Trim());

            Settings.Default.Save();
            MessageBox.Show("代码类文件生成完成，请到文件夹：" + txtPath.Text.Trim() + "中查看");

        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (fb.ShowDialog() == DialogResult.OK)
                txtPath.Text = fb.SelectedPath;
            Settings.Default.Save();

        }

        private void btnReload_Click(object sender, EventArgs e)
        {
            LoadDatas();
            Settings.Default.Save();
        }

        private readonly string t;
        private int rowIndex = -1;
        private void dgTables_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
                return;



            rowIndex = e.RowIndex;
            ShowColums(e.RowIndex);
            Settings.Default.Save();
        }

        private void txtTablePrefix_TextChanged(object sender, EventArgs e)
        {
            CreateFileHelper.tblNamePrefixToRemove = txtTblNamePrefixToRemove.Text.Trim();
            caches.Clear();
            RefreshColums();
            Settings.Default.Save();
        }

        private void chkRemove__CheckedChanged(object sender, EventArgs e)
        {
            CreateFileHelper.RemoveTableName_ = chkRemoveTableName_.Checked;
            caches.Clear();
            RefreshColums();
            Settings.Default.Save();
        }

        private void CamelCace_CheckedChanged(object sender, EventArgs e)
        {
            CreateFileHelper.CamelCaseName = chkCamelCaseName.Checked;
            caches.Clear();
            RefreshColums();
            Settings.Default.Save();
        }

        private void chkRemoveColumn__CheckedChanged(object sender, EventArgs e)
        {
            CreateFileHelper.RemoveColumnName_ = chkRemoveColumnName_.Checked;
            caches.Clear();
            RefreshColums();
            Settings.Default.Save();
        }

        private void txtNameSpace_TextChanged(object sender, EventArgs e)
        {
            CreateFileHelper.NameSpace = txtNameSpace.Text.Trim();
            caches.Clear();
            RefreshColums();
            Settings.Default.Save();
        }

        private void chkAll_CheckedChanged(object sender, EventArgs e)
        {
            if (chkAll.Checked)
                for (int i = 0; i < m_tables.Count; i++)
                {
                    dgTables.Rows[i].Cells[0].Value = dgTables.Rows[i].Visible;
                }
            else
                for (int i = 0; i < m_tables.Count; i++)
                {
                    dgTables.Rows[i].Cells[0].Value = false;
                }
            Settings.Default.Save();
        }

        private void chkOverrideGetHashCode_CheckedChanged(object sender, EventArgs e)
        {
            CreateFileHelper.OverrideGetHashCode = chkOverrideGetHashCode.Checked;
            caches.Clear();
            RefreshColums();
            Settings.Default.Save();
        }

        private void chkEquals_CheckedChanged(object sender, EventArgs e)
        {

            CreateFileHelper.OverrideEquals = chkOverrideEquals.Checked;
            caches.Clear();
            RefreshColums();
            Settings.Default.Save();
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            var keyword = textBox1.Text.Trim();
            var sc = chkCaseSensitive.Checked ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase;
            CurrencyManager myCM = (CurrencyManager)BindingContext[dgTables.DataSource];
            myCM.SuspendBinding();//挂起数据绑定  
            try
            {
                if (keyword.Length != 0)
                {
                    foreach (DataGridViewRow row in dgTables.Rows)
                    {
                        var tableName = row.Cells[1].Value.ToString();
                        if (!string.IsNullOrEmpty(tableName) && tableName.IndexOf(keyword, sc) != -1)
                        {
                            row.Visible = true;
                        }
                        else
                        {
                            row.Visible = false;
                        }
                    }
                }
                else
                {
                    foreach (DataGridViewRow row in dgTables.Rows)
                    {
                        row.Visible = true;
                    }
                }
            }
            finally
            {
                myCM.ResumeBinding();//恢复数据绑定  
            }

        }

        private void chkGenerateColumn_CheckedChanged(object sender, EventArgs e)
        {
            CreateFileHelper.GenerateColumn = chkGenerateColumn.Checked;
            caches.Clear();
            RefreshColums();
            Settings.Default.Save();
        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            Settings.Default.Save();
        }
    }
}
